package com.youlu.campus.service.ca;

import com.youlu.campus.entity.PayButtonConfigPage;
import com.youlu.campus.entity.PayConfigPage;
import com.youlu.campus.entity.ca.CaReceiveConfig;
import com.youlu.campus.entity.ca.UserSubActivity;
import com.youlu.campus.entity.ca.dto.CaReceiveSaveDTO;
import com.youlu.campus.entity.ca.dto.CaReceiveSearchDTO;
import com.youlu.campus.service.activity.impl.ActivityPayConfigService;
import com.youlu.campus.service.course.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : CaReceiveService
 * @description : [领取证书]
 * @createTime : [2022/9/6 16:53]
 */
@Service
@Slf4j
public class CaReceiveAdminService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ActivityPayConfigService activityPayConfigService;

    public CaReceiveConfig save(CaReceiveSaveDTO dto) {
        CaReceiveConfig config = new CaReceiveConfig();
        config.setName(dto.getName());
        config.setId(dto.getId());
        config.setImageUrl(dto.getImageUrl());
        config.setLinkUrl(dto.getLinkUrl());
        config.setValid(dto.getValid());
        config.setPriority(dto.getPriority());
        config.setCreatedTime(new Date());
        config.setDeleted(false);
        if (StringUtils.isNotBlank(dto.getActivityId())) {
            config.setActivityId(dto.getActivityId());
        }
        mongoTemplate.save(config);
        return config;
    }

    public Page<CaReceiveConfig> list(CaReceiveSearchDTO dto) {
        QueryWrapper query = new QueryWrapper();
        if (StringUtils.isNotBlank(dto.getName())) {
            query.like("name", dto.getName());
        }
        long count = mongoTemplate.count(query, CaReceiveConfig.class);
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        query.with(Sort.by(Sort.Order.desc("id")));
        List<CaReceiveConfig> list = mongoTemplate.find(query.with(pageRequest), CaReceiveConfig.class);
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    public List<CaReceiveConfig> littlePageInfo(String userId) {
        Date now = new Date();
        QueryWrapper query = new QueryWrapper();
        query.where("valid", true);
        query.with(Sort.by(Sort.Order.desc("priority")));
        List<CaReceiveConfig> list = mongoTemplate.find(query, CaReceiveConfig.class);
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        list.forEach(caReceiveConfig -> {
            if (StringUtils.isNotBlank(caReceiveConfig.getActivityId())) {
                buildCaReceiveConfig(now,caReceiveConfig);
            }
        });
        List<CaReceiveConfig> result = new ArrayList<>(list.size());
        List<CaReceiveConfig> endList = list.stream().filter(caReceiveConfig -> 3 == caReceiveConfig.getCaReceiveStatus()).sorted(Comparator.comparing(CaReceiveConfig::getPriority).reversed()).collect(Collectors.toList());
        List<CaReceiveConfig> validList = list.stream().filter(caReceiveConfig -> 3 != caReceiveConfig.getCaReceiveStatus()).sorted(Comparator.comparing(CaReceiveConfig::getPriority).reversed()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(validList)){
            result.addAll(validList);
            validList.clear();
        }
        if(CollectionUtils.isNotEmpty(endList)){
            result.addAll(endList);
            endList.clear();
        }
        List<String> aidList = list.stream().map(CaReceiveConfig::getActivityId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(aidList)){
            Query query1 = new Query(Criteria.where("activityId").in(aidList).and("userId").is(userId));
            List<UserSubActivity> subActivities = mongoTemplate.find(query1,UserSubActivity.class);
            Map<String,Integer> map = subActivities.stream().collect(Collectors.toMap(UserSubActivity::getActivityId,UserSubActivity::getSubStatus,(o1,o2)->o2));
            if(MapUtils.isNotEmpty(map)){
                for (CaReceiveConfig caReceiveConfig : result) {
                    Integer status = map.get(caReceiveConfig.getActivityId());
                    caReceiveConfig.setSubStatus(status == null?0:status);
                }
            }
        }
        return result;
    }

    private void buildCaReceiveConfig(Date now, CaReceiveConfig caReceiveConfig) {
        PayConfigPage payConfigPage = activityPayConfigService.findByActivityId(caReceiveConfig.getActivityId(), 1);
        if (Objects.nonNull(payConfigPage)) {
            List<PayButtonConfigPage> caReceiveButtonConfigList = payConfigPage.getPayButtonConfigList();
            if (CollectionUtils.isNotEmpty(caReceiveButtonConfigList)) {
                //通过领取时间排序最早开始时间获取第一个
                PayButtonConfigPage caReceiveButtonEarlyStartTime =
                        caReceiveButtonConfigList.stream().sorted(Comparator.comparing(PayButtonConfigPage::getStartTime)).findFirst().orElse(null);
                if (Objects.nonNull(caReceiveButtonEarlyStartTime)) {
                    //当前时间大于领取开始时间，领取进行中
                   if(now.after(caReceiveButtonEarlyStartTime.getStartTime())){
                       caReceiveConfig.setCaReceiveStatus(2);
                    }
                }
                //通过领取时间排序最晚获取第一个
                PayButtonConfigPage caReceiveButtonLastEndTime =
                        caReceiveButtonConfigList.stream().sorted(Comparator.comparing(PayButtonConfigPage::getEndTime).reversed()).findFirst().orElse(null);
                if (Objects.nonNull(caReceiveButtonLastEndTime)) {
                    //当前时间大于领取结束时间，领取已结束
                   if(now.after(caReceiveButtonLastEndTime.getEndTime())){
                       caReceiveConfig.setCaReceiveStatus(3);
                   }
                }



            }

        }


    }
}
